var Browser = new Object();

Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument != 'undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox") != -1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari") != -1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);

var listTable = new Object;
listTable.tableId = 'tableList';

listTable.AutoHandles = function () {
    if (typeof(pagerFilter) != 'undefined') {
        this.setSortFlag();
        this.handleFilterThead();
    }
}
$(document).on("mouseover mouseout", '.listTable_edit', function (event) {
    if (event.type == "mouseover") {
        $(this).addClass('hover');
    } else if (event.type == "mouseout") {
        $(this).removeClass('hover');
    }
})
$(document).on('click', '[name="checkboxes[]"]', function (e) {
    //alert($(this).parents('form').find('[name="checkboxes[]"]').size());
    var totalCount = $(this).parents('form').find('[name="checkboxes[]"]').size();
    var checkedCount = $(this).parents('form').find('[name="checkboxes[]"]:checked').size();
    if (checkedCount == totalCount) {
        $('[name="checkAll"]').each(function (index, element) {
            element.checked = true;
        });
    } else {
        $('[name="checkAll"]').each(function (index, element) {
            element.checked = false;
        });
    }
    listTable.handlebtns($(this));
})
$(document).on('click', '[ltb-btn="batch"]', function (evt) {
    evt.preventDefault();
    if ($(this).hasClass('disabled') || $(this).parents('li').hasClass('disabled')) {
        return false;
    }
    var option = $(this).attr('ltb-opt'),
        confirmTitle = $(this).attr('title');
    if (typeof(option) == 'undefined') return false;
    $(this).parents('form').find('input[name="action"]').val(option);
    if (typeof(confirmTitle) == 'undefined' || confirmTitle.length == 0) {
        confirmTitle = '确定要批量操作吗?';
    } else {
        confirmTitle = '确定要' + confirmTitle + '吗?';
    }
    if (!confirm(confirmTitle)) return false;
    $(this).parents('form').submit();
})

//列表下俩菜单删选
$(document).on('click', '.ltb_dropdown .dropdown-menu a', function (evt) {
    evt.preventDefault();
    //var lable = $(this).html();
    var field = $(this).parents('ul').attr('data-field');
    var value = $(this).attr('data-value');
    pagerFilter[field] = value; //alert([field, value]);
    listTable.loadList();
})
listTable.selectAll = function (obj, chk) {
    if (chk == null) {
        chk = 'checkboxes';
    }
    var objs = $(obj).parents('form').find('[name="' + chk + '[]"]');
    $(objs).each(function (index, element) {
        element.checked = obj.checked;
    });
    var objsAll = $(obj).parents('form').find('[name="checkAll"]');
    $(objsAll).each(function (index, element) {
        element.checked = obj.checked;
    });
    listTable.handlebtns(obj);
}
listTable.handlebtns = function (obj) {
    //切换提交按钮的禁用状态
    //alert($(obj).parents('form').find('[name="checkboxes[]"]:checked').size());
    var btns = $(obj).parents('form').find('[ltb-btn="batch"]');
    //alert([$('[ltb-btn="batch"]').length , $(btns).length]);
    if ($(btns).length > 0) {
        var disabled = true;
        if ($(obj).parents('form').find('[name="checkboxes[]"]:checked').size() > 0) {
            disabled = false;
        }
        $(btns).each(function (index, element) {
            if (element.tagName.toUpperCase() == 'INPUT') {
                $(element).prop('disabled', disabled);
            } else if (element.tagName.toUpperCase() == 'A') {
                if (disabled) {
                    //$(element).addClass('disabled');
                    $(element).parents('li').addClass('disabled');
                } else {
                    //$(element).removeClass('disabled');
                    $(element).parents('li').removeClass('disabled');
                }
            }
        });
    }
}

//设置表格筛选后表头样式
listTable.handleFilterThead = function () {
    for (var field in pagerFilter) {
        if (pagerFilter[field].length > 0 & pagerFilter[field] > 0) {
            if ($('[data-field="' + field + '"]').length > 0) {
                $('[data-field="' + field + '"]').parents('th').addClass('filter');
            }
        }
    }
}

/**
 * 创建一个可编辑区
 */
listTable.edit = function (obj, act, id) {
    var tag = obj.firstChild.tagName;
    if (typeof(tag) != "undefined" && tag.toLowerCase() == "input") {
        return;
    }

    /* 保存原始的内容 */
    var org = obj.innerHTML;
    var val = Browser.isIE ? obj.innerText : obj.textContent;

    /* 创建一个输入框 */
    var txt = document.createElement("INPUT");
    txt.value = (val == 'N/A') ? '' : val;
    txt.style.width = (obj.offsetWidth + 12) + "px";

    /* 隐藏对象中的内容，并将输入框加入到对象中 */
    obj.innerHTML = "";
    obj.appendChild(txt);
    txt.focus();

    /* 编辑区输入事件处理函数 */
    txt.onkeypress = function (e) {
        var evt = listTable.fixEvent(e);
        var obj = listTable.srcElement(e);

        if (evt.keyCode == 13) {
            obj.blur();

            return false;
        }

        if (evt.keyCode == 27) {
            obj.parentNode.innerHTML = org;
        }
    }

    /* 编辑区失去焦点的处理函数 */
    txt.onblur = function (e) {
        var txt_value = listTable.trim(txt.value);
        if (txt_value.length == 0 || txt_value == org) {
            obj.innerHTML = org;
        } else {
            var uri = BASE_URI+ '/' + pagerFilter.router;
            // var uri = pagerFilter.uri;
            uri += '/ajax/fast_edit/' + id + '?act=' + act;
            uri += '&val=' + encodeURIComponent(listTable.trim(txt.value));
            listTable.showLoader();
            $.getJSON(uri, function (res) {
                if ('undefined' == res || res.error > 0) {
                    alert(res.message);
                    obj.innerHTML = org;
                } else {
                    obj.innerHTML = res.content;
                }
                listTable.hideLoader();
            });
        }


        //res = Ajax.call(listTable.url, "act="+act+"&val=" + encodeURIComponent(Utils.trim(txt.value)) + "&id=" +id, null, "POST", "JSON", false);

        //if (res.message)
        //      {
        //        alert(res.message);
        //      }
    }
}

//=========================
/**
 * 切换排序方式
 */
listTable.sort = function (obj) {
    var sort_by = $(obj).attr('ltb-sort');
    if (typeof(sort_by) == "undefined") return false;
    if (pagerFilter.sort == sort_by) {
        sort_order = pagerFilter.order.toUpperCase() == "DESC" ? "ASC" : "DESC";
    } else {
        sort_order = 'DESC';
    }
    pagerFilter.sort = sort_by;
    pagerFilter.order = sort_order;
    this.loadList();
}
listTable.setSortFlag = function (e) {
    if (typeof(pagerFilter.sort) != "undefined") {
        var sort_order = typeof(pagerFilter.order) == "undefined" ? 'DESC' : pagerFilter.order;
        //var flagStr = '<span class="dropup"><span class="caret"></span></span>';
        var flagStr = '<span class="glyphicon glyphicon-arrow-up"></span>';
        if (sort_order.toUpperCase() == "DESC") {
            flagStr = '<span class="glyphicon glyphicon-arrow-down"></span>';
            //flagStr = '<span class="caret"></span>';
        }
        $('[ltb-sort="' + pagerFilter.sort + '"]').after(flagStr);
    }
}

/**
 * 翻页
 */
listTable.gotoPage = function (page) {
    page = typeof(page) == "undefined" ? 1 : page;
    if (page == 0) return false;
    pagerFilter.page = page;
    if (pagerFilter.page > pagerFilter.page_count) pagerFilter.page = 1;
    pagerFilter.page_size = this.getPageSize();
    this.loadList();
}
listTable.loadList = function (page) {
    //var href = location.href.lastIndexOf("?") == -1 ? location.href.substring((location.href.lastIndexOf("/")) + 1) : location.href.substring((location.href.lastIndexOf("/")) + 1, location.href.lastIndexOf("?"));
    var target = typeof(target) == "undefined" ? '#tableList' : target;
    if ($(target).length == 0) {
        return false;
    }
    href = pagerFilter.uri;
    pagerFilter.page = typeof(page) == "undefined" ? pagerFilter.page : page;
    if (href == '') {
        var uri = location.href;
        href = 'index';
    } else {
        var uri = href; //location.href.split(href)[0];
    }
    uri += '/ajax/query';

    if (typeof(pagerFilter) != "undefined") {
        uri += this.compileFilter(pagerFilter);
    }
    //$(target).html(uri);
    listTable.showLoader();
    $.getJSON(uri, function (res) {
        if ('undefined' == res || res.error > 0) {
            alert(res);
        } else {
            $(target).html(res.content);
            if ('undefined' != res.trash_count & $('#trash_count').length > 0) {
                $('#trash_count').html(res.trash_count);
            }
            //设置排序标识
            listTable.AutoHandles();
        }
        listTable.hideLoader();
    });
    return false;
}
listTable.compileFilter = function (filter) {
    var args = '?';
    for (var i in filter) {
        if (typeof(filter[i]) != "function" && typeof(filter[i]) != "undefined" && i != 'uri') { // && i != 'page'
            args += "&" + i + "=" + encodeURIComponent(filter[i]);
        }
    }
    return args.replace('?&', '?');
}

listTable.changePageSize = function (e) {
    var evt = listTable.fixEvent(e);
    if (evt.keyCode == 13) {
        this.gotoPage();
        return false;
    }
    ;
}
listTable.getPageSize = function () {
    var ps = 15; //alert(obj2str(pagerFilter));
    var pageSize = $("#pageSize").val();
    if (pageSize) {
        ps = this.isInt(pageSize) ? pageSize : 15;
        document.cookie = "LTPager[page_size]=" + ps + ";";
    }
    return ps;
}
listTable.confirmSubmit = function (frm, ext) {
    if ($(frm).find('input[name="checkboxes[]"]:checked').length == 0) {
        alert('未选中任何数据……');
        return false;
    }
    if ($(frm).find('select[name="type"]').val() == '') {
        return false;
    } else {
        return confirm($(frm).find('select[name="type"]>option:selected').attr('data-confirm-msg'));
    }
    return false;
}
listTable.showLoader = function () {
    if ($("#listTableLoader").length == 0) {
        $('body').append('<div id="listTableLoader">Loading......</div>');
    }
    //$("#listTableLoader").css({'position':'fixed', 'bottom':'50px', 'left':'50%', 'padding':'5px 10px', 'background-color':'#36c', 'color':'#fff', 'border':'1px solid #ddd', 'z-index':'999'}).hide();
    //$("#listTableLoader").animate({'bottom':'50px'});
    //$("#listTableLoader").append($("#listTableLoader").outerWidth()+':'+$(document).width());
    var _left = ($(document).width() - $("#listTableLoader").outerWidth()) / 2;
    $("#listTableLoader").css({
        'left': _left + 'px',
        'top': '5px'
    }).fadeIn('fast'); //.show().animate({'bottom':'50px'});//.fadeIn('slow');
    $("#listTableLoader").click(function () {
        listTable.hideLoader();
    });
}
listTable.hideLoader = function () {
    $("#listTableLoader").fadeOut(); //.hide();//.animate({'bottom':'-50px'});
}

//showLoader();
listTable.fixEvent = function (e) {
    var evt = (typeof e == "undefined") ? window.event : e;
    return evt;
}

listTable.srcElement = function (e) {
    if (typeof e == "undefined") e = window.event;
    var src = document.all ? e.srcElement : e.target;
    return src;
}
listTable.isInt = function (val) {
    if (val == "") {
        return false;
    }
    var reg = /\D+/;
    return !reg.test(val);
}
listTable.trim = function (text) {
    if (typeof(text) == "string") {
        return text.replace(/^\s*|\s*$/g, "");
    } else {
        return text;
    }
}
listTable.toggleTableCollapse = function (obj) {
    var found = false;
    var trEle = $(obj).parents('tbody').children('tr');
    var index = $(trEle).index($(obj).parents('tr')); //alert([$(trEle).length, index]);
    var level = $(obj).parents('tr').attr('data-level');
    var collapse = $(obj).hasClass('glyphicon-minus');
    while (true) {
        index++;
        if (index > $(trEle).length) break;
        if ($(trEle).eq(index).attr('data-level') > level) {
            if (collapse) {
                $(trEle).eq(index).hide();
            } else {
                var currIco = $(trEle).eq(index).find('.glyphicon');
                if ($(currIco).hasClass('glyphicon-plus')) {
                    $(currIco).removeClass('glyphicon-plus');
                    $(currIco).addClass('glyphicon-minus');
                }
                $(trEle).eq(index).show();
            }
        } else {
            break;
        }
    }
    if (collapse) {
        $(obj).removeClass('glyphicon-minus');
        $(obj).addClass('glyphicon-plus');
    } else {
        $(obj).removeClass('glyphicon-plus');
        $(obj).addClass('glyphicon-minus');
    }
}
//$('[data-action="listTable"]').on('mouseover', this, function(){
//	$(this).css({'background-color':'#1E8296', 'color':'#fff'});
//})
//$('[data-action="listTable"]').on('mouseout', this, function(){
//	$(this).css({'background-color':'#fff', 'color':'#000'});
//})

//$('[data-action="listTable"]').click(function(e) {
//    var tag = $(this).attr("tagName");alert(tag);
//	if (typeof(tag) != "undefined" && tag.toLowerCase() == "input"){
//		return;
//	}
//	 /* 保存原始的内容 */
//	var org = $(this).html();
//	/* 创建一个输入框 */
//	var txt = document.createElement("INPUT");
//	txt.value = org;
//	txt.style.width = ($(this).width() + 12) + "px" ;
//
//	/* 隐藏对象中的内容，并将输入框加入到对象中 */
//	$(this).html('');
//	$(this).append(txt);
//	txt.focus();
//});

/**
 * table 复选框联动事件
 */
listTable.privCheckAll = function (obj) {
    $(obj).parents('table').find('input[type="checkbox"]').not('[name="kickout"]').prop('checked', $(obj).prop('checked'));
}
listTable.privCheckRow = function (obj) {
    $(obj).parents('td').next('td').find('input[type="checkbox"]').prop('checked', $(obj).prop('checked'));
    this.privHandleChkAll(obj);
}
listTable.privCheck = function (obj) {
    var eleCount = $(obj).parents('td').find('input[type="checkbox"]').length;
    var chkCount = $(obj).parents('td').find('input[type="checkbox"]:checked').length;
    $(obj).parents('td').prev('td').find('input[type="checkbox"]').prop('checked', eleCount == chkCount);
    this.privHandleChkAll(obj);
}
listTable.privHandleChkAll = function (obj) {
    //全选按钮
    var allEleCount = $(obj).parents('table').find('input[type="checkbox"]').not('[name="chkAll"], [name="kickout"]').length;
    var allChkCount = $(obj).parents('table').find('input[type="checkbox"]:checked').not('[name="chkAll"], [name="kickout"]').length;
    $(obj).parents('table').find('input[name="chkAll"]').prop('checked', allEleCount == allChkCount);
}
$(function () {
    //设置排序标识
    listTable.AutoHandles();
})